//
//  UIColor+Util.m
//  wozhua
//
//  Created by 王洋 on 14-10-13.
//  Copyright (c) 2014年 王洋. All rights reserved.
//

#import "UIColor+Util.h"

static NSDictionary *kWZColor;

@implementation UIColor (Util)

+ (UIColor *)colorWithHexString:(NSString *)stringToConvert {
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];//字符串处理
    if ([cString length] < 6) {
        return [UIColor whiteColor];//如果非十六进制，返回白色
    }
    if ([cString hasPrefix:@"#"]) {
        cString = [cString substringFromIndex:1];//去掉头
    }
    if ([cString length] != 6) {
        return [UIColor whiteColor];//去头非十六进制，返回白色
    }
    
    //分别取RGB的值
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    unsigned int r, g, b;
    //NSScanner把扫描出的制定的字符串转换成Int类型
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    //转换为UIColor
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}

+ (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return theImage;
}



+ (UIColor *)colorWithString:(NSString *)string; {
    return [[self WZColorDic] objectForKey:string];
}

+ (NSString *)stringForColor:(UIColor *)color {
    if (!color) {
        return nil;
    }
    NSDictionary *colorDic = [self WZColorDic];
    NSArray *keys = [colorDic allKeys];
    NSString *colorStr = nil;
    for (int i = 0; i < keys.count; i ++) {
        UIColor *compareColor = [colorDic objectForKey:[keys objectAtIndex:i]];
        if (CGColorEqualToColor(color.CGColor, compareColor.CGColor)) {
            colorStr = [keys objectAtIndex:i];
            break;
        }
    }
    
    return colorStr;
}

 //MARK:颜色字符串
+ (NSDictionary *)WZColorDic {
    if (!kWZColor) {
        kWZColor = [[NSDictionary alloc] initWithObjectsAndKeys:
                    [UIColor whiteColor], @"main", nil];
    }
    
    return kWZColor;
}

@end
